package top.hcode.hoj;

import top.hcode.hoj.common.LazyDao;
import top.hcode.hoj.pojo.entity.org.TyOrg;
import top.hcode.hoj.tyedu.SyncSchoolOrgService;
import top.hcode.hoj.tyedu.SyncSchoolUserService;
import top.hcode.hoj.tyedu.TyGatewayClient;

import java.util.List;

/**
 * @author orangej
 * @since 2025/1/22
 */
public class TyDownloadOrgApp extends BaseDbApp {

    public static void main(String[] args) {
        LazyDao dao = buildLazyDao();
        TyGatewayClient client = buildClient();

        // 查询需要同步的学校（gmt_modified 为 null）
        List<TyOrg> schoolList = dao.selectList(TyOrg.class, "select * from ty_org where org_type = 2 and gmt_modified is null");

        for (TyOrg sch : schoolList) {
            String orgId = sch.getId();

            // 同步年级、班级信息
            SyncSchoolOrgService syncSchoolOrgService = new SyncSchoolOrgService(dao, client);
            syncSchoolOrgService.syncSchool(orgId);

            // 同步学生、教师信息
            SyncSchoolUserService syncSchoolUserService = new SyncSchoolUserService(dao, client);
            syncSchoolUserService.syncSchoolUser(orgId);

            // 更新 gmt_modified
            dao.runSql("update ty_org set gmt_modified = now() where id = ?", orgId);
        }

        // 重建 org_class
        rebuildOrgClass(dao);
    }

    private static void rebuildOrgClass(LazyDao dao) {
        dao.runSql("truncate table org_class");

        dao.runSql("insert into org_class (id, tree_code, class_name, class_num, grade_id, grade_num)\n" +
                   "select id, tree_code, org_name, class_num, parent_id, grade_num from org where org_type = 7;");
        dao.runSql("update org_class t0\n" +
                   "left join org t1 on substr(t0.tree_code, 1, 4) = t1.tree_code\n" +
                   "set t0.school_id = t1.id\n" +
                   "where t1.id is not null;");
        dao.runSql("update org_class t0\n" +
                   "left join org t1 on substr(t0.tree_code, 1, 8) = t1.tree_code\n" +
                   "set t0.campus_id = t1.id\n" +
                   "where t1.id is not null;");
    }

}
